package com.example.cangzhou.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cangzhou.entity.User;
import com.example.cangzhou.result.Result;
import com.example.cangzhou.service.UserService;
import com.example.cangzhou.vo.UserVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Tag(name = "用户接口", description = "用户接口")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserVo> login(@RequestBody UserVo userVo) {
        return userService.login(userVo.getAccount(), userVo.getPassword());
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result<UserVo> register(@RequestBody UserVo userVo) {
        return userService.register(userVo);
    }

    @PostMapping("/list")
    @Operation(summary = "用户列表（分页）")
    public Result<Page<User>> list(
            @RequestBody UserVo userVo,  // 查询条件
            @RequestParam(defaultValue = "1") Integer pageNum,  // 当前页
            @RequestParam(defaultValue = "10") Integer pageSize  // 每页条数
    ) {
        // 构造分页对象
        Page<User> page = new Page<>(pageNum, pageSize);
        // 执行分页查询（假设 userService 已注入）
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        Page<User> result = userService.pageList(page, user);
        return Result.success(result);
    }

    @PostMapping("/{id}")
    @Operation(summary = "用户删除")
    public Result<String> delete(@PathVariable Integer id ) {
        boolean success = userService.removeById(id);
        if (success) {
            return Result.success("用户删除成功");
        } else {
            return Result.error("用户不存在或删除失败");
        }
    }

    @PostMapping("/update")
    @Operation(summary = "用户更新")
    public Result<String> update(@RequestBody UserVo userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        boolean success = userService.updateById(user);
        if (success) {
            return Result.success("用户更新成功");
        } else {
            return Result.error("用户更新失败");
        }
    }

}
